package com.jikangjun.disk.file.service.impl;

import com.jikangjun.disk.file.entity.FileEntity;
import com.jikangjun.disk.file.entity.FileShareEntity;
import com.jikangjun.disk.file.entity.SearchFileEntity;
import com.jikangjun.disk.file.entity.FileCopyRequest;
import com.jikangjun.disk.file.entity.FileMoveRequest;
import com.jikangjun.disk.file.repository.FileDao;
import com.jikangjun.disk.file.service.FileService;
import com.jikangjun.disk.mybatis.entity.PtFileEntity;
import com.jikangjun.disk.mybatis.flexigrid.PagingEntity;
import com.jikangjun.disk.mybatis.flexigrid.TblResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

// 移除重复的import
// import com.jikangjun.disk.file.repository.FileDao;

@Service
public class FileServiceImpl implements FileService {
    // 将@Resource替换为@Autowired和@Qualifier
    @Autowired
    @Qualifier("repositoryFileDao") // 指定要注入的Bean名称
    private FileDao fileDao;
    @Override
    public void saveFileInfo(List<PtFileEntity> ptFileEntityList) {
        fileDao.deleteFileAll();
        fileDao.saveFileInfo(ptFileEntityList);

    }
    @Override
    public List<FileEntity> getUserFiles(String userId, String parentId) {
        // 如果parentId为空，默认查询根目录文件(parentId为null或空字符串)
        return fileDao.queryUserFiles(userId, parentId);
    }

    /**
     * 获取共享给用户的文件列表
     */
    @Override
    public List<FileShareEntity> getSharedFiles(String userId) {
        return fileDao.querySharedFiles(userId);
    }

    /**
     * 创建新文件夹
     */
    @Override
    public void createFolder(FileEntity folder) {
        fileDao.createFolder(folder);
    }

    /**
     * 获取文件详情
     */
    @Override
    public FileEntity getFileDetail(String fileId) {
        return fileDao.queryFileById(fileId);
    }

    @Override
    public TblResponseEntity<PtFileEntity> queryFileInfoListByPage(SearchFileEntity entity, PagingEntity paging) {
        TblResponseEntity<PtFileEntity> tblResponseEntity = new TblResponseEntity<>();
        Integer total = fileDao.queryFileListTotal(entity);
        tblResponseEntity.setTotal(total);
        //计算当前页数
        paging.deal(PtFileEntity.class,total);
        tblResponseEntity.setPage(paging.getPage());

        List<PtFileEntity> list = fileDao.queryFileInfoListByPage(entity,paging);
        tblResponseEntity.setRawRecords(list);

        tblResponseEntity.deal();
        return tblResponseEntity;
    }

    @Override
    public void copyFile(FileCopyRequest request) {
        // 查询源文件
        FileEntity source = fileDao.queryFileById(request.getSourceFileId());
        if (source == null) throw new RuntimeException("源文件不存在");
        
        // 检查目标目录是否存在同名文件
        String newFileName = source.getFileName();
        int counter = 1;
        while (fileDao.checkFileExists(newFileName, request.getTargetDirectoryId())) {
            // 如果存在同名文件，添加数字后缀
            String nameWithoutExt = source.getFileName();
            String extension = "";
            int lastDotIndex = source.getFileName().lastIndexOf('.');
            if (lastDotIndex > 0) {
                nameWithoutExt = source.getFileName().substring(0, lastDotIndex);
                extension = source.getFileName().substring(lastDotIndex);
            }
            newFileName = nameWithoutExt + " (" + counter + ")" + extension;
            counter++;
        }
        
        // 构造新文件对象
        FileEntity copy = new FileEntity();
        copy.setFileId(java.util.UUID.randomUUID().toString().replace("-", ""));
        copy.setFileName(newFileName);
        copy.setUserId(request.getUserId());
        copy.setParentId(request.getTargetDirectoryId());
        copy.setIsFolder(source.getIsFolder());
        copy.setCreateTime(new java.util.Date());
        copy.setUpdateTime(new java.util.Date());
        copy.setFileSize(source.getFileSize());
        copy.setFileType(source.getFileType());
        copy.setFileUrl(source.getFileUrl());
        
        // 插入新文件记录
        fileDao.insertFile(copy);
    }

    @Override
    public void moveFile(FileMoveRequest request) {
        FileEntity file = fileDao.queryFileById(request.getSourceFileId());
        if (file == null) throw new RuntimeException("源文件不存在");
        
        // 检查权限
        if (!file.getUserId().equals(request.getUserId())) {
            throw new RuntimeException("没有权限移动此文件");
        }
        
        // 检查目标目录是否存在同名文件
        String newFileName = file.getFileName();
        int counter = 1;
        while (fileDao.checkFileExists(newFileName, request.getTargetDirectoryId())) {
            // 如果存在同名文件，添加数字后缀
            String nameWithoutExt = file.getFileName();
            String extension = "";
            int lastDotIndex = file.getFileName().lastIndexOf('.');
            if (lastDotIndex > 0) {
                nameWithoutExt = file.getFileName().substring(0, lastDotIndex);
                extension = file.getFileName().substring(lastDotIndex);
            }
            newFileName = nameWithoutExt + " (" + counter + ")" + extension;
            counter++;
        }
        
        // 更新文件记录
        file.setParentId(request.getTargetDirectoryId());
        file.setFileName(newFileName);
        file.setUpdateTime(new java.util.Date());
        fileDao.updateFile(file);
    }
    @Override
    public void renameFile(String fileId, String newName, String userId) {
        // 检查文件是否存在
        FileEntity file = fileDao.queryFileById(fileId);
        if (file == null) {
            throw new RuntimeException("文件不存在");
        }
    
        // 检查权限
        if (!file.getUserId().equals(userId)) {
            throw new RuntimeException("没有权限修改此文件");
        }
    
        // 添加同名文件检查
        boolean exists = fileDao.checkFileExists(newName, file.getParentId());
        if (exists) {
            throw new RuntimeException("该目录下已存在同名文件");
        }
    
        // 更新文件名
        file.setFileName(newName);
        file.setUpdateTime(new java.util.Date());
        fileDao.updateFileName(fileId, newName);
    }

    @Override
    public List<PtFileEntity> queryFileListAll() {
        return fileDao.queryFileListAll();
    }

    /**
     * 检查文件是否存在
     */
    @Override
    public boolean checkFileExists(String fileName, String parentId) {
        return fileDao.checkFileExists(fileName, parentId);
    }

    /**
     * 插入文件记录
     */
    @Override
    public void insertFile(FileEntity file) {
        fileDao.insertFile(file);
    }

    /**
     * 删除文件记录
     */
    @Override
    public void deleteFile(String fileId) {
        fileDao.deleteFile(fileId);
    }

    /**
     * 将文件移动到回收站
     */
    @Override
    public void moveToRecycle(String fileId, String userId) {
        // 检查文件是否存在
        FileEntity file = fileDao.queryFileById(fileId);
        if (file == null) {
            throw new RuntimeException("文件不存在");
        }

        // 检查权限
        if (!file.getUserId().equals(userId)) {
            throw new RuntimeException("没有权限删除此文件");
        }

        // 将文件移动到回收站（这里可以调用回收站服务）
        // 暂时直接删除文件记录，实际实现可能需要移动到回收站表
        fileDao.deleteFile(fileId);
    }

    @Override
    public PtFileEntity queryFileInfoById(String fileUuid) {
        return fileDao.queryFileInfoById(fileUuid);
    }
}
